package org.example.backupexchange;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: anlu
 * @Date: 2021/07/06
 * @Description: 主要消费者
 */
public class MainConsumer {
    public static void main(String[] args)throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");

        // 打开连接和创建信道
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();

        // 声明一个队列
        String queueName = "focuserror";
        channel.queueDeclare(queueName,false,false  ,false,null);

        String routeKey = "error";
        // 绑定：将队列和交换器用路由键进行绑定
        channel.queueBind(queueName,BackupExProducer.EXCHANGE_NAME,routeKey);
        System.out.println(" Waiting for messages......");

        // 创建队列的消费者
        final Consumer consumerB = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                //记录日志到文件：
                System.out.println( "Received ["
                        + envelope.getRoutingKey() + "] "+message);
            }
        };
        // 消费消息
        channel.basicConsume(queueName, true, consumerB);
    }
}
